<template>
  <div class="status-management">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="openDialog('create')">新增</el-button>
      <el-button
        type="success"
        @click="batchEnable"
        :disabled="selectedRows.length === 0"
        >启用</el-button
      >
      <el-button
        type="danger"
        @click="batchDisable"
        :disabled="selectedRows.length === 0"
        >禁用</el-button
      >
    </div>

    <!-- 项目状态表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 16px"
      :header-cell-style="{ background: '#F8F9FA' }"
      @selection-change="handleSelection"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-icon
            @click="openDialog('edit', scope.row)"
            style="cursor: pointer; margin-right: 8px"
          >
            <Edit />
          </el-icon>
          <el-icon
            @click="deleteRow(scope.row)"
            style="cursor: pointer; color: red"
          >
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" min-width="120" sortable />
      <el-table-column label="启用状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
            {{ scope.row.enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="200" />
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'create' ? '保存项目状态' : '编辑项目状态'"
      width="400px"
    >
      <el-form
        :model="form"
        label-width="80px"
        :rules="formRules"
        ref="formRef"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注内容"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTag } from "element-plus";
import { Edit, Delete } from "@element-plus/icons-vue";

// ========== 核心数据 ==========
const tableData = ref([
  {
    id: 1,
    name: "繁荣",
    enabled: false, // 启用状态：false=禁用，true=启用
    remark: "你打开拉萨",
  },
]);

const selectedRows = ref([]); // 选中的行（用于批量操作）

// ========== 弹窗状态 ==========
const dialog = reactive({
  visible: false,
  type: "create", // create/edit
  origin: {}, // 编辑时存储原始数据
});

const form = reactive({
  name: "",
  remark: "",
});

// ========== 表单校验 ==========
const formRules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
};

// ========== 方法逻辑 ==========
/** 打开弹窗（新增/编辑） */
const openDialog = (type, row) => {
  dialog.type = type;
  dialog.visible = true;
  if (type === "create") {
    form.name = "";
    form.remark = "";
  } else {
    form.name = row.name;
    form.remark = row.remark;
    dialog.origin = { ...row };
  }
};

/** 保存表单（新增/编辑） */
const saveForm = () => {
  if (!form.name) {
    ElMessage.warning("名称为必填项");
    return;
  }
  if (dialog.type === "create") {
    // 新增：生成唯一ID（模拟）
    const newId = Date.now();
    tableData.value.push({
      id: newId,
      name: form.name,
      enabled: false, // 新增默认禁用
      remark: form.remark,
    });
    ElMessage.success("项目状态新增成功！");
  } else {
    // 编辑：更新数据
    const index = tableData.value.findIndex(
      (item) => item.id === dialog.origin.id
    );
    if (index === -1) {
      ElMessage.error("数据异常，请刷新重试");
      return;
    }
    tableData.value[index].name = form.name;
    tableData.value[index].remark = form.remark;
    ElMessage.success("项目状态编辑成功！");
  }
  dialog.visible = false;
};

/** 批量启用 */
const batchEnable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要启用的项目");
    return;
  }
  selectedRows.value.forEach((row) => {
    row.enabled = true;
  });
  ElMessage.success("选中项目已启用！");
};

/** 批量禁用 */
const batchDisable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要禁用的项目");
    return;
  }
  selectedRows.value.forEach((row) => {
    row.enabled = false;
  });
  ElMessage.success("选中项目已禁用！");
};

/** 单行删除 */
const deleteRow = (row) => {
  ElMessageBox.confirm("确定删除该项目状态吗？", "警告", { type: "warning" })
    .then(() => {
      tableData.value = tableData.value.filter((item) => item.id !== row.id);
      ElMessage.success("删除成功！");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/** 多选事件 */
const handleSelection = (val) => {
  selectedRows.value = val;
};

// ========== 初始化 ==========
onMounted(() => {
  // 模拟数据加载（可替换为接口请求）
  tableData.value = [
    {
      id: 1,
      name: "繁荣",
      enabled: false,
      remark: "你打开拉萨",
    },
  ];
});
</script>

<style scoped>
.status-management {
  padding: 24px;
  background: #fff;
}

.action-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}

/* 操作图标样式 */
.el-icon {
  font-size: 18px;
  cursor: pointer;
}
</style>